<template>
  <div class="new-register-box">
    <div class="main-box">
      <div class="center-form" v-if="!registerSuccess">
        <el-form
          ref="registerFromData"
          class="register-form"
          :rules="registerFormRules"
          :model="registerFromData"
          label-width="80px"
          autocomplete='off'
        >
          <el-form-item label="手机号：" prop="phone">
            <el-input
              class="phone-input"
              maxlength='11'
              type='tel'
              placeholder="请输入手机号码"
              v-model="registerFromData.phone"
            />
          </el-form-item>
          <el-form-item label="验证码：" prop="capcha">
            <div class="capcha-corver">
              <el-input
                v-model.trim="registerFromData.capcha"
                placeholder="请输入手机验证码"
                maxlength="6"
                class="capcha-input"
              >
                <el-button
                 v-if="codeShow"
                  class="capcha-button"
                  type="primary"
                  slot="suffix"
                  :disabled="sendCodeDiabled"
                  @click="sendCode"
                  :loading="codeLoading"
                  >{{ sendCodeTitle }}</el-button>
                  <el-button
                  v-if="timoutShow"
                  class="capcha-button"
                  type="primary"
                  slot="suffix"
                  :disabled="sendCodeDiabled"
                  >{{ sendCodeTitle }}</el-button>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item label="密码：" prop="password">
            <el-input
              v-model.trim="registerFromData.password"
              placeholder="请设置6-16位字母、数字"
              clearable
              show-password
              maxlength="20"
              class="password-input"
              autocomplete='new-password'
              type="password"
            />
          </el-form-item>
          <el-form-item>
            <el-checkbox class="agreement-checkbox" v-model="registerFromData.agreeToRegister"
              >已阅读并同意</el-checkbox
            >
            <span class="service-agreement" @click="showService('PLATFORM_SERVICE')"
              >《服务协议》</span
            >
            <span class="privacy-agreement" @click="showPrivacy('PRIVACY_POLICY')"
              >《隐私政策》</span
            >
          </el-form-item>
          <el-form-item>
            <el-button class="register-immediate" @click="submitRegister"
              >立即注册</el-button
            >
          </el-form-item>
          <el-form-item>
            <p class="has-account">
              已有账号？<span @click="goLogin">立即登录>></span>
            </p>
          </el-form-item>
        </el-form>
      </div>
      <div class="register-success" v-else>
        <img :src="successIcon" alt="" />
        <p>注册成功</p>
        <p>立即企业认证成为会员，即可进行正常操作。</p>
        <div class="button-area">
          <el-button class="verify-immediate">立即认证</el-button>
          <el-button class="go-home">去首页</el-button>
        </div>
      </div>
    </div>
    <el-dialog
      :visible.sync="serviceAgreementVisible"
      width="60%"
      :show-close="false"
      :close-on-click-modal="false"
      >
      <span v-html="agreementData.agreementContent || ''">{{agreementData.agreementContent || ''}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="serviceAgreementVisible = false">取 消</el-button>
        <el-button type="primary" @click="readAgreement(agreementData.id)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import cookie from 'js-cookie'
import md5 from 'js-md5'
import {phone} from '@const/formValidate.js'
import { setTimeout, setInterval, clearTimeout } from 'timers';
import {
  sendRegistVerificationCode,
  getByAgreementCodeList,
  simpleRegisterUser
} from '@const/api_staffCenter.js';
export default {
  layout: 'login',
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (!/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/.test(value)) {
          callback(new Error('请设置6-16位字母、数字'))
          return false
        }
        // if (this.registerFromData.password !== '') {
        //   this.$refs.registerFromData.validateField('password')
        // }
        callback()
      }
    }
    return {
      successIcon: require('@assets/img/login/success-icon.png'),
      registerFromData: {
        phone: '',
        capcha: '',
        password: '',
        agreeToRegister: ''
      },
      registerFormRules: {
        phone: phone(),
        capcha: [
          {required: true, message: '请输入验证码', trigger: 'blur'},
          {
            pattern: /^[0-9]{6}$/,
            message: '请输入6位数字验证码',
            trigger: 'blur'
          }
        ],
        password: [{required: true, validator: validatePass, trigger: 'blur'}]
      },
      sendCodeDiabled: false,
      codeLoading: false,
      sendCodeTitle: '获取验证码',
      registerSuccess: false,
      timout: '',
      codeShow: true,
      timoutShow: false,
      time: 60,
      serviceAgreement: '', // 服务协议
      privacyAgreement: '', //隐私协议
      agreementName: '',
      serviceAgreementVisible: false,
      privacyAgreementVisible: false,
      agreementCodeList:[],
      agreementData: '',
      agreementList:[],
      // sendVerificationCodeFlag: false
    }
  },
  methods: {
    // 发送验证码
    sendCode() {
      if (!/^1[23456789]\d{9}$/.test(this.registerFromData.phone)) {
        this.$message({
          type: 'warning',
          message: '请输入正确的手机号'
        })
        return
      }
      this.$refs.registerFromData.validateField('phone',(msg) => {
        console.log(msg)
        if(!msg) {
          // this.sendVerificationCodeFlag = true
          this.$axios({
            url: sendRegistVerificationCode,
            method: 'post',
            data: {
              phone: this.registerFromData.phone,
              source: 'm_pc_web'
            }
          })
          .then(res => {
            if (res.data.code === '0') {
              this.codeShow = false
              this.timoutShow = true
              this.timout = setInterval(()=>{
                let time = this.time;
                time = time - 1
                this.time = time
                this.sendCodeTitle = `${this.time}秒后重发`
                if (this.time === 0) {
                  clearTimeout(this.timout)
                  this.time = false
                  this.codeShow = true
                  this.time = 60
                  this.timoutShow = false
                  this.sendCodeTitle = '重新获取'
                }
              },1000)
              this.$message({type: 'success', message: '验证码发送成功！'})
            }
          })
          .catch(err => {
            // reject(err);
          });
        }
      })
    },
    submitRegister() {
      // if (!this.sendVerificationCodeFlag){
      //   this.$message({type: 'success', message: '请获取验证码'})
      //   return false
      // }
      console.log('====this.$refs:', this.registerFromData)
      this.$refs['registerFromData'].validate(valid => {
        if (!this.registerFromData.agreeToRegister) {
          this.$message({type: 'success', message: '请阅读协议'})
          return false
        }
        let parms = JSON.parse(JSON.stringify(this.registerFromData))
        parms.verificationCode = this.registerFromData.capcha || ''
        parms.source = 'm_pc_web'
        parms.agreementList = this.agreementList
        parms.password = md5(parms.password)
        console.log('====valid:', valid)
        if (valid) { 
          this.$axios({
            url: simpleRegisterUser,
            method: 'post',
            data: parms
          })
            .then(res => {
              if (res.data.code === '0') {
                this.$message({type: 'success', message: '注册成功'})
                this.$store.commit('login', res.data.payload || {});
                // window.location.href = '/#/business/'
                let curryCompanyId = cookie.get('companyId') || ''
                console.log('curryCompanyId:', curryCompanyId)
                if (curryCompanyId === '0') {
                  window.location.href = '/#/business/'
                } else {
                  window.location.href = '/'
                }
              }
            })
            .catch(err => {
              // reject(err);
            });
        }
      })
    },
    // 打开服务协议
    showService(agreementType) {
      this.agreementData = this.agreementCodeList.filter((a) => {
          return a.agreementCode === agreementType
        }
      )
      this.agreementData = this.agreementData[0]
      this.serviceAgreementVisible = true;
    },
    // 隐私政策
    showPrivacy(agreementType ) {
      this.agreementData = this.agreementCodeList.filter((a) => {
          return a.agreementCode === agreementType
        }
      )
      this.agreementData = this.agreementData[0] || {}
      this.serviceAgreementVisible = true;
    },
    // 去登录
    goLogin() {
      this.$router.push({
        path: this.$PATH_CONST.login_page
      })
    },
    getagreementCodeList() {
      this.$axios({
        url: getByAgreementCodeList,
        method: 'get',
        data: {}
      })
        .then(res => {
          if (res.data.code === '0') {
            this.agreementCodeList = res.data.payload || []
            this.agreementList = (res.data.payload || []).map (a => {
              return a.id
            })
          }
        })
        .catch(err => {
          // reject(err);
        });
    },
    readAgreement(id) {
      if (!this.agreementList.includes(id)) {
        this.agreementList.push(id)
      }
      this.serviceAgreementVisible = false
      console.log('==this.agreementList:', this.agreementList)
    }
  },
  mounted() {
    if(cookie.get('smsLoginPhone')) {
      this.registerFromData.phone = cookie.get('smsLoginPhone')
      cookie.remove('smsLoginPhone')
    }
    if(cookie.get('smsLoginCode')) {
      this.registerFromData.capcha = cookie.get('smsLoginCode')
      cookie.remove('smsLoginCode')
    }
    this.getagreementCodeList()
  },
  created() {
    this.$store.commit('setLoginTitle', '注册账号')
  }
}
</script>
<style lang="less">
.new-register-box {
  font-family: PingFangSC-Regular;
  background:
    #f4f6fb
    url('../../../m-front-common/pc/assets/img/home/registerbg1.png') no-repeat
    100% 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  .main-box {
    min-width: 460px;
    min-height: 320px;
    width: 822px;
    height: 505px;
    background: white;
    display: flex;
    justify-content: center;
    align-items: center;
    .register-success {
      display: flex;
      flex-direction: column;
      align-items: center;
      img {
        width: 80px;
        height: 70px;
      }
      p:nth-of-type(1) {
        font-family: PingFangSC-Regular;
        font-size: 32px;
        color: #4d84ff;
        letter-spacing: 0;
        margin: 16px 0 11px 0;
      }
      p:nth-of-type(2) {
        font-family: PingFangSC-Regular;
        font-size: 18px;
        color: #666;
        letter-spacing: 0;
        text-align: right;
      }
      .button-area {
        width: 330px;
        display: flex;
        justify-content: space-around;
        margin-top: 40px;
        .go-home {
          width: 114px;
          height: 42px;
          background: #f4f4f4;
          border: 1px solid #ccc;
          border-radius: 4px;
          border-radius: 4px;
          font-size: 16px;
          color: #666;
          letter-spacing: 0;
        }
        .verify-immediate {
          width: 114px;
          height: 42px;
          background: #4d84ff;
          border-radius: 4px;
          font-size: 16px;
          color: #fff;
          letter-spacing: 0;
        }
      }
    }
    .center-form {
      .service-agreement,
      .privacy-agreement {
        font-size: 12px;
        color: #4d84ff;
        letter-spacing: 0;
        line-height: 17px;
        &:hover {
          cursor: pointer;
        }
      }
      .agreement-checkbox {
        &:hover {
          cursor: pointer;
        }
      }
      .register-immediate {
        font-size: 16px;
        color: #fff;
        letter-spacing: 0;
        width: 330px;
        height: 40px;
        background: #4d84ff;
        border-color: #4d84ff;
        border-radius: 4px;
        border-radius: 4px;
        font-weight: 100;
        font-family: PingFangSC-Regular;
      }
      .has-account {
        font-size: 14px;
        color: #333;
        letter-spacing: 0;
        line-height: 20px;
        span {
          color: #4d84ff;
          &:hover {
            cursor: pointer;
          }
        }
      }
      .capcha-button {
        width: 120px;
        height: 38px;
        background: #f4f4f4;
        border-left: 1px solid #ccc;
        border-radius: 0 2px 2px 0;
        border-top: none;
        border-right: none;
        border-bottom: none;
        font-size: 14px;
        color: #666;
        letter-spacing: 0;
        margin-right: -4px;
        font-weight: 100;
        font-family: PingFangSC-Regular;
      }
    }
  }
  // element表单重置
  .el-checkbox__input.is-checked .el-checkbox__inner{
    background-color: #4d84ff;
    border-color: #4d84ff;
  }
  .el-checkbox__input.is-checked+.el-checkbox__label{
    color: #333333;
  }
  .el-input__inner {
    width: 330px;
    height: 40px;
    border-radius: 2px;
    border: 1px solid #ccc;
  }
  .el-checkbox__label {
    font-size: 12px;
  }
  .el-dialog__header{
    display: none
  }
  .dialog-footer{
   display: flex; 
   justify-content: center;
   align-items: center;
   .el-button{
     height: 42px;
     width: 114px;
     border-radius: 4px;
     span{
       font-weight: 0;
     }
     &:nth-child(1) {
        background: #F4F4F4;
        font-family: PingFangSC-Regular;
        font-size: 16px;
        color: #666666;
        margin-right: 16px;
     }
     &:nth-child(2) {
        background: #4D84FF;
        font-family: PingFangSC-Regular;
        font-size: 16px;
        color: #FFFFFF;
        margin-left: 16px;
     }
   }
  }
}
</style>
